/*
 * This file is part of the SDWebImage package.
 * (c) Olivier Poitrey <rs@dailymotion.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

#import "UIImageView+WebCache.h"
#import "SDWebImageManager.h"
#import <CommonCrypto/CommonHMAC.h>
#import "SupportFunction.h"// MinhPB 2012/06/28
#import <objc/runtime.h>

@implementation UIImageView (WebCache)
static char UIB_PROPERTY_KEY;
@dynamic scaleOption;

- (void)setScaleOption:(NSString *)option
{
    objc_setAssociatedObject(self, &UIB_PROPERTY_KEY, option, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (NSString *)scaleOption
{
    return (NSString *)objc_getAssociatedObject(self, &UIB_PROPERTY_KEY);
}

- (void)setImageWithURL:(NSURL *)url
{
    [self setImageWithURL:url placeholderImage:nil];
    
}

- (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder
{
    // MinhPB 2013/01/26
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString *path = [documentsDirectory stringByAppendingPathComponent:url.absoluteString];
    if([fileManager fileExistsAtPath:path])
    {
        // SET LOCAL FILE
        UIImage *localImage = [UIImage imageNamed:url.absoluteString];
        if ([self.scaleOption isEqual: enumWebImageScaleOption_FullFill]) {
            [self setImage:localImage];
        }
        else if ([self.scaleOption isEqual: enumWebImageScaleOption_Center_ScaleSize]) {
            [self setImage:[localImage imageByScalingToSize:self.frame.size withOption:enumImageScalingType_Center_ScaleSize]];
        }
        else if ([self.scaleOption isEqual: enumWebImageScaleOption_ScaleToWidth_Top]) {
            [self setImage:[localImage imageByScalingToSize:self.frame.size withOption:enumImageScalingType_Top]];
        }
        else if ([self.scaleOption isEqual: enumWebImageScaleOption_Center_FullSize]) {
            [self setImage:[localImage imageByScalingToSize:self.frame.size withOption:enumImageScalingType_Center_FullSize]];
        }
        else {
            [self setImage:localImage];
        }
        return;
    }
    
    SDWebImageManager *manager = [SDWebImageManager sharedManager];
    
    // Remove in progress downloader from queue
    [manager cancelForDelegate:self];
    
    // MinhPB 03/07/2012
    if ([self.scaleOption isEqual: enumWebImageScaleOption_FullFill]) {
        [self setImage:placeholder];
    }
    else if ([self.scaleOption isEqual: enumWebImageScaleOption_Center_ScaleSize]) {
        [self setImage:[placeholder imageByScalingToSize:self.frame.size withOption:enumImageScalingType_Center_ScaleSize]];
    }
    else if ([self.scaleOption isEqual: enumWebImageScaleOption_ScaleToWidth_Top]) {
        [self setImage:[placeholder imageByScalingToSize:self.frame.size withOption:enumImageScalingType_Top]];
    }
    else if ([self.scaleOption isEqual: enumWebImageScaleOption_Center_FullSize]) {
        [self setImage:[placeholder imageByScalingToSize:self.frame.size withOption:enumImageScalingType_Center_FullSize]];
    }
    else {
        [self setImage:placeholder];
    }
    
    //     // added by seng
    //     UIActivityIndicatorView *activityView = [[[UIActivityIndicatorView alloc]
    //     initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray] autorelease];
    //     activityView.frame = CGRectMake((CGRectGetWidth(self.frame) / 2 - 11.0f),CGRectGetHeight(self.frame) / 2, 22.0f, 22.0f);
    //
    //     activityView.autoresizingMask = UIViewAutoresizingFlexibleRightMargin |
    //     UIViewAutoresizingFlexibleBottomMargin |
    //     UIViewAutoresizingFlexibleLeftMargin |
    //     UIViewAutoresizingFlexibleTopMargin;
    //
    //     [self addSubview: activityView];
    //     [activityView startAnimating];
    
    
    if (url)
    {
        // MinhPB 2012/10/04
        [manager downloadWithURL:url delegate:self retryFailed:YES];
    }
    
}

- (void)webImageManager:(SDWebImageManager *)imageManager didFinishWithImage:(UIImage *)image
{
    // MinhPB 03/07/2012
    if ([self.scaleOption isEqual: enumWebImageScaleOption_FullFill]) {
        [self setImage:image];
    }
    else if ([self.scaleOption isEqual: enumWebImageScaleOption_Center_ScaleSize]) {
        [self setImage:[image imageByScalingToSize:self.frame.size withOption:enumImageScalingType_Center_ScaleSize]];
    }
    else if ([self.scaleOption isEqual: enumWebImageScaleOption_ScaleToWidth_Top]) {
        [self setImage:[image imageByScalingToSize:self.frame.size withOption:enumImageScalingType_Top]];
    }
    else if ([self.scaleOption isEqual: enumWebImageScaleOption_Center_FullSize]) {
        [self setImage:[image imageByScalingToSize:self.frame.size withOption:enumImageScalingType_Center_FullSize]];
    }
    else {
        [self setImage:image];
    }
    
    NSArray *subviews = [self subviews];
    UIActivityIndicatorView *activityView = nil;
    for (activityView in subviews)
    {
        if ([activityView isKindOfClass:[UIActivityIndicatorView class]])
        {
            [activityView stopAnimating];
            [activityView removeFromSuperview];
        }
    }
}

-(void)webImageManager:(SDWebImageManager *)imageManager didFailWithError:(NSError *)error{
    
    /*if(!self.image){
     NSLog(@"TAG FAIL = %d", self.tag);
     NSDictionary *userInfo = [[NSDictionary alloc] initWithObjectsAndKeys:[NSString stringWithFormat:@"%d",self.tag],@"index", nil];
     [[NSNotificationCenter defaultCenter] postNotificationName:@"DownloadError" object:nil userInfo:userInfo];
     }
     else{
     UIImageView *imageTemp = [[UIImageView alloc]initWithImage:self.image];
     imageTemp.tag = self.tag;
     NSLog(@"TAG = %d", self.tag);
     
     [[NSNotificationCenter defaultCenter] postNotificationName:@"FinishDownloadImage" object:imageTemp userInfo:nil];
     
     
     }*/
    
    // MinhPB 02/07/2012
    NSArray *subviews = [self subviews];
    UIActivityIndicatorView *activityView = nil;
    for (activityView in subviews)
    {
        if ([activityView isKindOfClass:[UIActivityIndicatorView class]])
        {
            [activityView stopAnimating];
            [activityView removeFromSuperview];
        }
    }
}

@end
